package org.openintents.oiserverdemo;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;

import android.database.Cursor;
import android.util.Log;

import com.googlecode.jatl.Html;

public class HTMLFileGenerator {
	
	private File dir;
	private Cursor notesCursor;
	private Html html;
	
	public HTMLFileGenerator(File dir) {
		this.dir = dir;
	}
	
	/**
	 * Generates all the HTML files for all OI applications
	 * @param notesCursor
	 * @throws IOException
	 */
	
	public void generateFiles(Cursor notesCursor) throws IOException {
		this.notesCursor = notesCursor;
		Log.d("org.openintents.oiserverdemo", "**** GENERATING ****");
		File indexFile = new File(dir.getAbsolutePath()+"/index.html");
		if(!indexFile.exists())
			indexFile.createNewFile();
		generateIndexFile(indexFile);
		File oiNotepadFile = new File(dir.getAbsolutePath()+"/oinotepad.html");
		generateNotepadFile(oiNotepadFile, notesCursor);
	}
	
	/**
	 * Generates main index file that has a link to each OI application
	 * @param f
	 * @throws IOException
	 */
	
	private void generateIndexFile(File f) throws IOException {
		StringWriter writer = new StringWriter();
		html = new Html(writer) {{
			html();
			head();
			title().text("OIServerDemo").end();
			end();
			body();
			h1().text("OIServerDemo").end();
			p().text("OpenIntent Applications").end();
			ul().id("appList");
				li().a().href("oinotepad.html").text("OI Notepad").end().end();
			end();
			p();
				a().href("index.html").text("Home").end();
			end();
			endAll();
		}};
		writeToFile(f.getAbsolutePath(), writer.toString());
		writer.close();
	}
	
	/**
	 * Generates the main index file for OI Notepad that contains all the notes stored in OI Notepad
	 * @param f
	 * @throws IOException
	 */
	
	public void generateNotepadFile(File f, final Cursor notesCursor) throws IOException {
		StringWriter writer = new StringWriter();
		html = new Html(writer) {{
			html();
			head();
			title().text("OIServerDemo - OI Notepad").end();
			end();
			body();
			h1().text("OI Notepad").end();
			p().text("OI Notepad Notes").end();
			ol().id("noteList");
			
			notesCursor.moveToFirst();
			do {
					String title = notesCursor.getString(notesCursor.getColumnIndex("TITLE"));
					int id = notesCursor.getShort(notesCursor.getColumnIndex("_ID"));
					Log.d("org.openintens.oiserverdemo", "ID: "+id+" TITLE: "+title);
					li().a().href("note"+id+".html").text(title).end().end();
					generateNote(id, title, notesCursor.getString(notesCursor.getColumnIndex("NOTE")).trim());
			} while(notesCursor.moveToNext());
			end();
			p();
				a().href("index.html").text("Home").end();
			end();
			end();
			endAll();
		}};
		writeToFile(f.getAbsolutePath(), writer.toString());
		writer.close();
	}
	
	/**
	 * Generates a HTML content file that has the notes contents specified by {id}
	 * File name of the file is note{id}.html
	 * @param id
	 * @param title
	 * @param text
	 * @throws IOException
	 */
	
	private void generateNote(final int id, final String title, final String text) throws IOException{
		String note = dir.getAbsolutePath()+"/note"+id+".html";
		StringWriter writer = new StringWriter();
		InputStream istr = OIServerDemoActivity.mContext.getAssets().open("jquery.js");
		OutputStream ostr = new FileOutputStream(dir.getAbsolutePath()+"/jquery.js");
		byte[] buffer = new byte[4096];
		int len;
		while((len = istr.read(buffer)) != -1) {
			ostr.write(buffer, 0, len);
		}
		istr.close();
		ostr.close();
		
		html = new Html(writer) {{
			html();
			head();
			title().text("OIServerDemo - OI Notepad - "+title).end();
			script().src("jquery.js").type("text/javascript").end();
			script().text("$(function() { $('#editButton').click(function() {" +
					"$('#noteText').hide(); $('#edit').show();" +
					"})});").end();
			end();
			body();
				h1().text(title).end();
				pre().id("noteText").text(text).end();
				button().id("editButton").text("Edit").end();
				div().id("edit").style("display:none");
					form().method("GET").action("/update");
						input().type("hidden").value(Integer.toString(id)).name("id");
						table();
							tr();
								td();
									textarea().name("text").style("width:400px; height:100px;").text(text).end();
								end();
							end();
							tr();
								td();
									button().type("submit").name("submit").text("Save").end();
								end();
							end();
						end();
					end();
				end();
				div().id("footer");
					p();
						a().href("index.html").text("Home").end();
						raw("&nbsp;&nbsp;&nbsp;&nbsp;");
						a().href("oinotepad.html").text("OI Notepad Home").end();
					end();
				end();
			endAll();
		}};
		
		writeToFile(note, writer.toString());
		writer.close();
	}
	
	/**
	 * Writes {data} to the file {f}
	 * @param f
	 * @param data
	 * @throws IOException
	 */
	
	private void writeToFile(String f, String data) throws IOException {
		BufferedWriter fout = new BufferedWriter(new FileWriter(f));
		fout.write(data);
		fout.flush();
		fout.close();
	}
	
	public static String generateInfo(final String title, final String text) {
		StringWriter writer = new StringWriter();
		Html html = new Html(writer) {{
			html();
			head();
			title().text("OIServerDemo - OI Notepad - "+title).end();
			end();
			body();
				h1().text(title).end();
				p().text(text).end();
				p();
				a().href("index.html").text("Home").end();
				raw("&nbsp;&nbsp;&nbsp;&nbsp;");
				a().href("oinotepad.html").text("OI Notepad Home").end();
			endAll();
		}};
		
		return writer.toString();
	}
	
	public static String generateInfoRedirect(final String title, final String text, 
			final int delay, final String dest) {
		StringWriter writer = new StringWriter();
		Html html = new Html(writer) {{
			html();
			head();
			title().text("OIServerDemo - OI Notepad - "+title).end();
			raw("<META HTTP-EQUIV=\"refresh\" CONTENT=\""+Integer.toString(delay)+";URL="+dest+"\">");
			end();
			body();
				h1().text(title).end();
				p().text(text).end();
				p().text("You will be redirected in "+Integer.toString(delay)+" seconds ");
				a().href(dest).text("click here").end();
				text(" if you are not automatically redirected");
				end();
			endAll();
		}};
		
		return writer.toString();
	}
}
